<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :closable="getClosable"
    :show-cancel-btn="getClosable"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
import type { Ref } from 'vue';
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountPwdFormSchema } from './account.data';
import { encryptByMd5, strongPwdRegex } from '/@/utils/cipher';
import {
  getDistrictList,
  editAccountPwd,
  addAccountList,
  isAccountExist,
} from '/@/api/demo/system';

import { useUserStore } from '/@/store/modules/user';

export default defineComponent({
  name: 'AccountPwdModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    const isCloseable = ref(true);
    const rowId = ref('');
    const rowName = ref('');
    const refListDist = ref([]) as Ref<any[]>;
    const userStore = useUserStore();

    const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
      labelWidth: 100,
      size: 'small',
      schemas: accountPwdFormSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
    });

    function findAllNodes(val: any[], valOri: String[], jurisdictionCodes: String[]) {
      valOri.forEach((element) => {
        let fd = val.find((x) => x.id == element);
        if (fd) {
          if (jurisdictionCodes.indexOf(fd.regionCode) < 0) {
            jurisdictionCodes.push(fd.regionCode);
          }
          findAllNodes(val, [fd.parentId], jurisdictionCodes);
        }
      });
    }

    const AccValidator = function (_, value, _callback) {
      if (!value) {
        _callback();
        return;
      }

      isAccountExist(value)
        .then((d) => {
          if (d) {
            _callback('用户已存在');
          } else {
            _callback();
          }
        })
        .catch((err) => {
          _callback(err.message || '验证失败');
        });
    };

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      isCloseable.value = !!data?.closeable;
      rowId.value = data.record.number;
    });

    const getTitle = computed(() => '修改密码1');

    const getClosable = computed(() => isCloseable.value);

    async function handleSubmit() {
      try {
        const values = await validate();

        //const allCodes = [];

        //findAllNodes(refListDist.value, values.jurisdictionCodes, allCodes);
        //values.jurisdictionCodes = allCodes;
        setModalProps({ confirmLoading: true });
        // TODO custom api
        values.userNumber = rowId.value;
        const pwdOri = values.pwd;
        values.pwd = encryptByMd5(values.pwd);
        console.log('************************', values.pwd)
        await editAccountPwd(values);

        const pwdGood = strongPwdRegex.test(pwdOri);
        userStore.setGoodPassword(pwdGood);
        console.log(values);
        closeModal();
        emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
      } catch (ex) {
        console.log(ex);
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerModal, registerForm, getTitle, getClosable, handleSubmit };
  },
});
</script>
